<template>
<div>
  <el-form ref="userForm" :model="form" :rules="rules" label-width="80px" class="login-box">
    <el-input placeholder="请输入新密码" v-model="form.newpwd" show-password prop="newpwd"></el-input>
    <el-button type="primary" v-on:click="changePwd('userForm')">确认</el-button>
  </el-form>
</div>
</template>

<script>

import { ChangePwd } from "@/api/changePwd.js";
import conf from "@/utils/config.js";
const { token } = conf;

export default {
  name: "changePwd",
  props:['id'],
  data() {
    return {
      form:{
        username: '',
        newpwd:''
      },
      rules: {
        newpwd: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ]
      },
    }
  },
  mounted: function() {
    // 这里是将list2参数的值赋给list1
    this.form.username = JSON.parse(JSON.stringify(this.id));
    console.log(this.form.username);
    console.log(this.id);
  },
  methods: {
    changePwd(userform){
      //为表单绑定验证功能
      this.$refs[userform].validate((valid) => {
        // console.log(valid);
        if (valid) {
          // 验证通过 提交数据给后台 存token 路由跳转
          // token 单纯存在sessionStorage、localStorage、cookie是可行的  若存在vuex中 刷新页面就没了
          ChangePwd(this.form)
            .then((res) => {
              console.log(res);

              //返回值格式 {"age":1,"id":1,"name":"zxc"}  注意 不是{fname:"John",lname:"Doe",age:25}这种格式
              var jsonObj = eval('('+res.request.response +')');
              console.log(jsonObj.code);
              // 存token setItem(key,value)
              if (jsonObj.code == 200) {
                //sessionStorage.setItem(token, res.data.token);
                this.$notify.success({
                  title: "修改成功！",
                  message: res.statusText,
                });
              } else if(jsonObj.code == 400){
                console.log(res.statusText);
                // statusText是后台写好的提示
                this.$notify.error({
                  title: "错误",
                  message: res.statusText,
                });
              }
            })
            .catch((err) => {
              this.$notify.error({
                title: "错误",
                message: "服务器内部错误",
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>
.box-card {
  width: 480px;
}

</style>
